package su.msk.jet.team01.chatik.common;

import java.util.HashMap;
import java.util.Map;

public final class ArgsExtractor {
	private final Map<String, String> args = new HashMap<String, String>();
	private String currentArg = "";

	public ArgsExtractor(final String[] strs) {
		extract(strs);
	}

	public String getArg(final String arg) {
		return getArg(arg, "");
	}

	public String getArg(final String arg, final String defaultValue) {
		String strArgs = args.get(arg);

		if (strArgs != null) {
			return strArgs;
		}

		return defaultValue;
	}

	public Map<String, String> getArgs() {
		return args;
	}

	private void addKey(final String key, final String value) {
		args.put(key, value);
	}

	private void extract(final String[] strs) {
		for (String str : strs) {
			parseWord(str);
		}
		saveParameterKey();
	}

	private String getParameterKey(final String str) {
		return str.substring(1, str.length());
	}

	private boolean isParameterKey(final String str) {
		return str.length() > 1 && str.startsWith("-");
	}

	private void parseWord(final String str) {
		if (isParameterKey(str)) {
			saveParameterKey();
			currentArg = getParameterKey(str);
		} else {
			saveParameterKey(str);
			currentArg = "";
		}
	}

	private void saveParameterKey() {
		saveParameterKey("true");
	}

	private void saveParameterKey(final String value) {
		if (!currentArg.isEmpty()) {
			addKey(currentArg, value);
		}
		currentArg = "";
	}
}
